/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.job.admin.common;

import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.config.RegistryConfig;
import com.lvyh.lightframe.job.admin.bean.JobTaskDefBean;
import com.lvyh.lightframe.job.admin.processor.JobManageProcessor;
import com.lvyh.lightframe.job.admin.util.SpringContextUtils;
import com.lvyh.lightframe.job.enums.TaskType;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * Connect to the zookeeper registry of the Dubbo service.
 * Dynamically encapsulate the information of Dubbo service into local variables.
 */
@Service
public class RegistryContainer {

    /**
     * Encapsulate the services of all providers,
     * The map structure is <Interface full class name , Service address list>
     */
    private final Map<String, List<String>> serviceProviders = new ConcurrentHashMap<String, List<String>>();

    /**
     * Get all provider information
     */
    public Map<String, List<String>> getServiceProviders() {
        return Collections.unmodifiableMap(serviceProviders);
    }

    /**
     * Get the address list of the provider according to the interface name
     */
    public List<String> getProvidersByService(String service) {
        List<String> urls = serviceProviders.get(service);
        return urls == null ? null : Collections.unmodifiableList(urls);
    }


    /**
     * The method executed when the container is initialized.
     * When the servlet container initializes, it requests the registry and encapsulates the data in the registry into local variables
     */
    @PostConstruct
    public void start() throws Exception {
        JobManageProcessor jobManageProcessor = SpringContextUtils.getBean(JobManageProcessor.class);
        RegistryConfig registryConfig = SpringContextUtils.getBean(RegistryConfig.class);
        List<JobTaskDefBean> taskDefs = jobManageProcessor.getJobTaskDefList();

        String zkServerAddr = registryConfig.getAddress().replace("zookeeper://", "");
        ZkClient zkClient = new ZkClient(zkServerAddr);
        for (JobTaskDefBean bean : taskDefs) {
            if (bean.getTaskType() != TaskType.DUBBO.getType()) {
                continue;
            }

            String dubboServiceName = bean.getDubboService();
            String dataId = "/dubbo/" + dubboServiceName + "/providers";

            // Subscribe to the service provider information under the path and add listener
            List<String> list = zkClient.subscribeChildChanges(dataId, new IZkChildListener() {
                @Override
                public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
                    parseIpList(dubboServiceName, serviceProviders, currentChilds);
                }
            });

            parseIpList(dubboServiceName, serviceProviders, list);
        }
    }


    private static List<URL> toUrlsWithoutEmpty(List<String> providers) {
        List<URL> urls = new ArrayList<URL>();
        if (providers != null && providers.size() > 0) {
            urls = providers.stream().map(provider -> URL.decode(provider)).filter(provider -> provider.contains("://"))
                    .map(provider -> URL.valueOf(provider))
                    .collect(Collectors.toList());
        }

        return urls;
    }

    /**
     * Resolve the service provider address list to IP: Port format
     */
    private void parseIpList(String dubboServiceName, Map<String, List<String>> serviceProviders, List<String> ipSet) {
        List<URL> urlList = toUrlsWithoutEmpty(ipSet);
        final List<String> ipListTemp = urlList.stream().map(url -> url.getAddress()).collect(Collectors.toList());
        serviceProviders.put(dubboServiceName, ipListTemp);
    }

    @PreDestroy
    public void stop() throws Exception {

    }

}
